package torrent;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Torrent {
  
  //Info
  public String fileName;
  //in KB
  public int pieceLength;
  public String hashPieces;
  public ArrayList<String> arrPieces;  
  public long fileLength;
  public int pieceCount;
  //Announce
  public String uniformResourcesLocator;
  
  
  //Constructor
  public Torrent (File f) {
    fileName = f.getName();
    fileLength = f.length();    
  }
  
  public Torrent(){
      arrPieces = new ArrayList<>();
  }

    public void readFileTorrent(File file){
            try {
            char buffer;                
      DataInputStream diStream;
      try (BufferedReader fin = new BufferedReader(new FileReader(file))) {
        diStream = new DataInputStream((new FileInputStream(file)));
        StringTokenizer st;
        st = new StringTokenizer(fin.readLine());
        this.uniformResourcesLocator = st.nextToken();
        st = new StringTokenizer(fin.readLine());
        this.fileName = st.nextToken();
        st = new StringTokenizer(fin.readLine());
        this.fileLength = (long)Integer.parseInt(st.nextToken());
        st = new StringTokenizer(fin.readLine());
        this.pieceLength = Integer.parseInt(st.nextToken());
        st = new StringTokenizer(fin.readLine());
        this.pieceCount = Integer.parseInt(st.nextToken());
        for(int i=0; i<this.pieceCount; i++){
            st = new StringTokenizer(fin.readLine());                  
            this.arrPieces.add(st.nextToken());
        }
      }
              diStream.close();              
            } catch (FileNotFoundException ex) {
              System.out.println(ex);
            } catch (IOException e) {
              System.out.println(e);
            }               
    }  
  
    public String writeFileTorrent(File file, String URL, int pieceSize, int fileL, String piece){
        String hasil = "";
        try{
        fileName = file.getName();        
        fileLength = fileL;
        uniformResourcesLocator = URL;
        hashPieces = piece;
        pieceLength = pieceSize;
        pieceCount = (int)fileLength/pieceLength;
        if(pieceCount==0){pieceCount = 1;}
        hasil = uniformResourcesLocator + "\n" + fileName + "\n" + fileLength + "\n" + pieceLength + "\n" + pieceCount + "\n" + piece;
        }catch (Exception e){//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
        return hasil;
    }
  
    public static byte[] FileToByte(File file){
        //File file = new File(namafile);
        byte fileContent[] = new byte[(int)file.length()];
        try
        {
            //create FileInputStream object
            FileInputStream fin = new FileInputStream(file);
            fin.read(fileContent);

        }
        catch(FileNotFoundException e)
        {
          System.out.println("File not found" + e);
        }
        catch(IOException ioe)
        {
          System.out.println("Exception while reading the file " + ioe);
        }
        return fileContent;
    }    
    
    public static byte[] stringToByte(String data){
        char[] arrchar = data.toCharArray();
        byte[] hasil = new byte[arrchar.length];
        for (int i = 0; i < arrchar.length; i++){
            hasil[i] = (byte)arrchar[i];
        }
        return hasil;
    }

    private static String byteToHex(byte[] data) {
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                if ((0 <= halfbyte) && (halfbyte <= 9))
                    buf.append((char) ('0' + halfbyte));
                else
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while(two_halfs++ < 1);
        }
        return buf.toString();
    }

    public static String SHA1(byte[] text)
    throws NoSuchAlgorithmException, UnsupportedEncodingException  {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-1");
        //byte[] sha1hash = new byte[10];
        md.update(text, 0, text.length);
        byte[] sha1hash = md.digest();
        return byteToHex(sha1hash);
    }

    public static String SHA1b(byte[] text, int pieceLength)
    throws NoSuchAlgorithmException, UnsupportedEncodingException  {
        String result="";
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-1");
        //byte[] sha1hash = new byte[10];
        int pieceCount = text.length/pieceLength; 
        if(pieceCount==0){pieceCount=1;}
        for (int i=0; i<pieceCount; i++){
            if((text.length-i*pieceLength) >= pieceLength){
                md.update(text, i*pieceLength, pieceLength);
            }else{
                md.update(text, i*pieceLength, (text.length-i*pieceLength));
            }
            byte[] sha1hash = md.digest();
            result = result + byteToHex(sha1hash) + "\n";
        }
        return result;
    }  
  
}